import csv
from django.core.management import BaseCommand

from interview.models import Candidate


# python manage.py import_candidate --path ...

class Command(BaseCommand):
    help = "从一个csv文件中读取候选人信息导入到数据库中"

    def add_arguments(self, parser):
        parser.add_argument('--path', type=str)

    def handle(self, *args, **kwargs):
        path = kwargs['path']

        # rt模式下，python在读取文本时会自动把\r\n转换成\n，文本文件用二进制读取用‘rt’；不创建，不存在会报错。
        with open(path, 'rt', encoding='gbk') as f:
            reader = csv.reader(f, dialect="excel")
            # 　csv文件默认使用,分割;如果不能需在reader()加上delimeter=';'参数

            for row in reader:
                candidater = Candidate.objects.create(
                    username=row[0],
                    city=row[1],
                    phone=row[2],
                    bachelor_school=row[3],
                    major=row[4],
                    degree=row[5],
                    test_score_of_general_ability=row[6],
                    paper_score=row[7]
                )
                print(candidater)
